﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using DevExpress.XtraPrinting;
using GeneralLibs;
using CustomSecurity;
using System.Collections;

namespace ReportGenerators.QuanLyQuy
{
    public partial class FrmSoQuyTienMat : BasicForms.FrmSupportPrintableComponents
    {
        public FrmSoQuyTienMat()
        {
            InitializeComponent();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                //switch (keyData)
                //{
                //    case Keys.Delete:
                //        DeleteRow();
                //        break;
                //}
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private DataTable _GridDataSouce
        {
            get
            {
                if (gridControl.DataSource is DataTable)
                    return gridControl.DataSource as DataTable;
                else if (gridControl.DataSource is DataView)
                    return (gridControl.DataSource as DataView).ToTable();
                else
                    return null;
            }
        }

        private void FrmSoQuyTienMat_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                #region cmbTaiKhoan
                DataView dvTaiKhoan = DanhMucTaiKhoan.GetByLoaiTaiKhoan(LoaiTaiKhoan.TienMat).DataView;
                cmbTaiKhoan.DataSource = dvTaiKhoan;
                cmbTaiKhoan.DisplayColumn = "Ten";
                cmbTaiKhoan.ValueColumn = "ID";
                cmbTaiKhoan.AddVisibleColumn("SoHieu", "Số hiệu");
                cmbTaiKhoan.AddVisibleColumn("Ten", "Tên");
                cmbTaiKhoan.Buttons[1].Visible = false;
                #endregion

                cmbTaiKhoan.EditValue = DanhMucTaiKhoan.Instance.GetBySoHieu("1111").ID;

                cmbKyBaoCao.SelectedText = "Tùy chọn";

                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                {
                    column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                    column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                }

                //FormatGridViewForCopyCell(gridView); //KCB thì cho copy trong các report
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void gridView_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; //DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if (!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            string kyBaoCao = cmbKyBaoCao.Text;
            if (kyBaoCao == "Cả năm") kyBaoCao = "Năm " + GeneralLibs.Config.NamTaiChinh.ToString();
            else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                       ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                       ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            DataSet ds = new DataSet();
            try
            {
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;
                con.Open();
                SqlDataAdapter da = null;

                TaiKhoan taiKhoan = DanhMucTaiKhoan.Instance.GetByID((Guid)cmbTaiKhoan.EditValue);

                DataTable dtChiTietSoQuyTienMat = new DataTable("ChiTietSoQuyTienMat");
                dtChiTietSoQuyTienMat.Columns.Add("KyBaoCao", Type.GetType("System.String"));
                dtChiTietSoQuyTienMat.Columns.Add("TaiKhoan", Type.GetType("System.String"));
                dtChiTietSoQuyTienMat.Columns.Add("DuNoDauKy", Type.GetType("System.Decimal"));
                dtChiTietSoQuyTienMat.Rows.Add(dtChiTietSoQuyTienMat.NewRow());
                dtChiTietSoQuyTienMat.Rows[0]["KyBaoCao"] = kyBaoCao;
                dtChiTietSoQuyTienMat.Rows[0]["TaiKhoan"] = taiKhoan.SoHieu;
                dtChiTietSoQuyTienMat.Rows[0]["DuNoDauKy"] = SoDuTaiKhoan.CalculateFromDB(cmd, ngayBatDau, taiKhoan.ID).DuNo;
                ds.Tables.Add(dtChiTietSoQuyTienMat);

                if (chkThongKePhieuChi.Checked && chkThongKePhieuThu.Checked)
                {
                    cmd.CommandText = string.Format("	SELECT A.Ngay, A.NgayGhiSo, D.So AS SoHieuChungTuThu, N'' AS SoHieuChungTuChi, A.DienGiai, D.Text1 NhomLyDo, C.SoHieu AS SoHieuTaiKhoanDoiUng, \n" +
                                                "		GiaTri AS No,  CAST(0 AS  money)  AS Co,  CAST(0 AS  money)  AS Ton \n" +
                                                "	FROM ButToan A LEFT JOIN GhiNo ON A.ID = GhiNo.ButToanID \n" +
                                                "			--LEFT JOIN TaiKhoan B ON A.TaiKhoanNoID = B.ID \n" +
                                                "			LEFT JOIN TaiKhoan C ON A.TaiKhoanCoID = C.ID \n" +
                                                "			LEFT JOIN ChungTu D ON A.ChungTuID = D.ChungTuID \n" +
                                                "	WHERE GhiNo.TaiKhoanID = @TaiKhoanID AND @NgayBatDau <= A.Ngay AND A.Ngay <=@NgayKetThuc \n" +
                                                "	UNION  \n" +
                                                "	SELECT A.Ngay, A.NgayGhiSo, N'' AS SoHieuChungTuThu, D.So AS SoHieuChungTuChi, A.DienGiai, D.Text1 NhomLyDo, C.SoHieu AS SoHieuTaiKhoanDoiUng, \n" +
                                                "		  CAST(0 AS  money)  AS No, GiaTri AS Co, CAST(0 AS  money) AS Ton \n" +
                                                "	FROM ButToan A INNER JOIN GhiCo ON A.ID = GhiCo.ButToanID \n" +
                                                "			--LEFT JOIN TaiKhoan B ON A.TaiKhoanCoID = B.ID \n" +
                                                "			LEFT JOIN TaiKhoan C ON A.TaiKhoanNoID = C.ID \n" +
                                                "			LEFT JOIN ChungTu D ON A.ChungTuID = D.ChungTuID \n" +
                                                "	WHERE GhiCo.TaiKhoanID = @TaiKhoanID AND @NgayBatDau <= A.Ngay AND A.Ngay <=@NgayKetThuc \n" +
                                                "	ORDER BY A.Ngay \n");

                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("TaiKhoanID", taiKhoan.ID);
                    cmd.Parameters.AddWithValue("NgayBatDau", ngayBatDau.AddSeconds(1));
                    cmd.Parameters.AddWithValue("NgayKetThuc", ngayKetThuc);
                    da = new SqlDataAdapter(cmd);
                    da.Fill(ds, "KhoanMucSoQuyTienMat");

                    colSoTon.Visible = true;
                }
                else
                {
                    if (chkThongKePhieuThu.Checked)
                    {
                        cmd.CommandText = string.Format("	SELECT A.Ngay, A.NgayGhiSo, D.So AS SoHieuChungTuThu, N'' AS SoHieuChungTuChi, A.DienGiai, D.Text1 NhomLyDo, C.SoHieu AS SoHieuTaiKhoanDoiUng, \n" +
                                                        "		GiaTri AS No,  CAST(0 AS  money)  AS Co,  CAST(0 AS  money)  AS Ton \n" +
                                                        "	FROM ButToan A LEFT JOIN GhiNo ON A.ID = GhiNo.ButToanID \n" +
                                                        "			--LEFT JOIN TaiKhoan B ON A.TaiKhoanNoID = B.ID \n" +
                                                        "			LEFT JOIN TaiKhoan C ON A.TaiKhoanCoID = C.ID \n" +
                                                        "			LEFT JOIN ChungTu D ON A.ChungTuID = D.ChungTuID \n" +
                                                        "	WHERE GhiNo.TaiKhoanID = @TaiKhoanID AND @NgayBatDau <= A.Ngay AND A.Ngay <=@NgayKetThuc \n");

                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddWithValue("TaiKhoanID", taiKhoan.ID);
                        cmd.Parameters.AddWithValue("NgayBatDau", ngayBatDau.AddSeconds(1));
                        cmd.Parameters.AddWithValue("NgayKetThuc", ngayKetThuc);
                        da = new SqlDataAdapter(cmd);
                        da.Fill(ds, "KhoanMucSoQuyTienMat");
                        colSoTon.Visible = false;
                    }
                    else if (chkThongKePhieuChi.Checked)
                    {
                        cmd.CommandText = string.Format("	SELECT A.Ngay, A.NgayGhiSo, N'' AS SoHieuChungTuThu, D.So AS SoHieuChungTuChi, A.DienGiai, D.Text1 NhomLyDo, C.SoHieu AS SoHieuTaiKhoanDoiUng, \n" +
                                                       "		  CAST(0 AS  money)  AS No, GiaTri AS Co, CAST(0 AS  money) AS Ton \n" +
                                                       "	FROM ButToan A INNER JOIN GhiCo ON A.ID = GhiCo.ButToanID \n" +
                                                       "			--LEFT JOIN TaiKhoan B ON A.TaiKhoanCoID = B.ID \n" +
                                                       "			LEFT JOIN TaiKhoan C ON A.TaiKhoanNoID = C.ID \n" +
                                                       "			LEFT JOIN ChungTu D ON A.ChungTuID = D.ChungTuID \n" +
                                                       "	WHERE GhiCo.TaiKhoanID = @TaiKhoanID AND @NgayBatDau <= A.Ngay AND A.Ngay <=@NgayKetThuc \n" +
                                                       "	ORDER BY A.Ngay \n");

                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddWithValue("TaiKhoanID", taiKhoan.ID);
                        cmd.Parameters.AddWithValue("NgayBatDau", ngayBatDau.AddSeconds(1));
                        cmd.Parameters.AddWithValue("NgayKetThuc", ngayKetThuc);
                        da = new SqlDataAdapter(cmd);
                        da.Fill(ds, "KhoanMucSoQuyTienMat");
                        colSoTon.Visible = false;
                    }
                }

                decimal tonHienTai = (decimal)dtChiTietSoQuyTienMat.Rows[0]["DuNoDauKy"];

                foreach (DataRow row in ds.Tables["KhoanMucSoQuyTienMat"].Rows)
                {
                    if ((decimal)row["No"] > 0)
                    {
                        tonHienTai = tonHienTai + (decimal)row["No"];
                        row["Ton"] = tonHienTai;
                    }
                    else
                    {
                        tonHienTai = tonHienTai - (decimal)row["Co"];
                        row["Ton"] = tonHienTai;
                    }
                }

                gridControl.DataSource = ds.Tables["KhoanMucSoQuyTienMat"];

                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            try
            {
                string option1 = string.Format("Từ {0}:{1} ngày {2}/{3}/{4} đến {5}:{6} ngày {7}/{8}/{9}",
                                dtNgayBatDau.DateTime.Hour, dtNgayBatDau.DateTime.Minute,
                                dtNgayBatDau.DateTime.Day, dtNgayBatDau.DateTime.Month, dtNgayBatDau.DateTime.Year,
                                dtNgayKetThuc.DateTime.Hour, dtNgayKetThuc.DateTime.Minute,
                                dtNgayKetThuc.DateTime.Day, dtNgayKetThuc.DateTime.Month, dtNgayKetThuc.DateTime.Year);
                string option2 = "";

                gridView.OptionsPrint.MaxMergedCellHeight = -1;  //Để in ra cũng merge cell y như gridcontrol
                PrintWithHeaderAndFooter(true, gridControl, true, true, "Sổ quỹ tiền mặt", option1, option2, "", "");
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                //PrintClinic print = new PrintClinic();
                //if (_GridDataSouce != null)
                //    print.PrintBangKeThue(_GridDataSouce);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        //Event cho cả 3 radio luôn. Cụ thể thì sẽ xử lý bên trong
        private void rdoGroup_CheckedChanged(object sender, EventArgs e)
        {
            NhomTheoTieuChi();
        }
        private void btnBoNhom_Click(object sender, EventArgs e)
        {
            rdoGroupByLyDo.Checked = false;
        }
        private void NhomTheoTieuChi()
        {
            try
            {
                //Ban đầu vào re group hết đi rồi group lại
                gridView.OptionsView.ShowGroupPanel = false;
                gridView.OptionsCustomization.AllowGroup = false;
                gridView.OptionsBehavior.AutoExpandAllGroups = false;

                gridView.Columns["NhomLyDo"].SortOrder = DevExpress.Data.ColumnSortOrder.None;
                gridView.Columns["NhomLyDo"].OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.False;
                gridView.Columns["NhomLyDo"].UnGroup();

                gridView.GroupSummary.Clear();
                gridView.GroupFooterShowMode = DevExpress.XtraGrid.Views.Grid.GroupFooterShowMode.Hidden;

                //Group lại theo tiêu chí
                if (rdoGroupByLyDo.Checked)
                {
                    //code để group theo nhóm
                    gridView.OptionsView.ShowGroupPanel = true;
                    gridView.OptionsCustomization.AllowGroup = true;
                    gridView.OptionsBehavior.AutoExpandAllGroups = false;
                    gridView.Columns["NhomLyDo"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
                    gridView.Columns["NhomLyDo"].OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.True;
                    gridView.Columns["NhomLyDo"].Group();

                    gridView.GroupSummary.Clear();
                    gridView.GroupFooterShowMode = DevExpress.XtraGrid.Views.Grid.GroupFooterShowMode.VisibleIfExpanded;

                    // Hiện tổng tiền theo nhóm
                    DevExpress.XtraGrid.GridGroupSummaryItem item = new DevExpress.XtraGrid.GridGroupSummaryItem();
                    item.FieldName = "No";
                    item.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                    item.DisplayFormat = " (Tổng thu = {0:### ### ### ###})";
                    item.Tag = "No";
                    gridView.GroupSummary.Add(item);
                    DevExpress.XtraGrid.GridGroupSummaryItem item2 = new DevExpress.XtraGrid.GridGroupSummaryItem();
                    item2.FieldName = "Co";
                    item2.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                    item2.DisplayFormat = " (Tổng chi = {0:### ### ### ###})";
                    item2.Tag = "Co";
                    gridView.GroupSummary.Add(item2);
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
    }
}
